package com.laoxu.microservice.orderservice.service;

import com.laoxu.microservice.orderservice.pojo.Order;
import com.laoxu.microservice.orderservice.pojo.OrderDetail;
import com.laoxu.microservice.orderservice.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @description: 订单服务
 * @author: luohanye
 * @create: 2019-10-20
 **/
@Service
public class OrderService {
    private static final Map<String, Order> MAP = new HashMap<String, Order>();

    static {
        // 构造测试数据
        Order order = new Order();
        order.setOrderId("SA201911200000001");
        order.setCreateDate(new Date());
        order.setUpdateDate(order.getCreateDate());
        order.setUserId(1L);
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();

        Product product = new Product();// 此处并没有商品的数据，需要调用商品微服务获取
        product.setId(1L);
        orderDetails.add(new OrderDetail(order.getOrderId(), product));

        product = new Product(); // 构造第二个商品数据
        product.setId(2L);
        orderDetails.add(new OrderDetail(order.getOrderId(), product));

        order.setOrderDetails(orderDetails);

        MAP.put(order.getOrderId(), order);
    }

    @Autowired
    private ProductService productService;

    /**
     * 根据订单id查询订单数据
     *
     * @param orderId
     * @return
     */
    public Order queryOrderById(String orderId) {
        Order order = MAP.get(orderId);
        if (null == order) {
            return null;
        }
        List<OrderDetail> orderDetails = order.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            // 通过商品微服务查询商品数据
            Product product = this.productService.queryProductById(orderDetail.getProduct()
                    .getId());
            if (null == product) {
                continue;
            }
            orderDetail.setProduct(product);
        }

        return order;
    }
}
